﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BoneImp {
	class ScaleTimeline : BaseTimeline{
		public ScaleTimeline(int frameCount) : base(frameCount, 3) {}

		public override void apply(SkeletonBase skeleton, float time, float alpha) {
			if (time < this.frames[0]) return; /* Time is before first frame. */

			Bone bone = skeleton.bones[this.boneIndex];
			if (time >= this.frames[this.framesLength - 3]) { /* Time is after last frame. */
				bone.scaleX += (bone.data.scaleX - 1 + this.frames[this.framesLength - 2] - bone.scaleX) * alpha;
				bone.scaleY += (bone.data.scaleY - 1 + this.frames[this.framesLength - 1] - bone.scaleY) * alpha;
				return;
			}

			/* Interpolate between the last frame and the current frame. */
			int frameIndex = binarySearch(this.frames, this.framesLength, time, 3);
			float lastFrameX = this.frames[frameIndex - 2];
			float lastFrameY = this.frames[frameIndex - 1];
			float frameTime = this.frames[frameIndex];
			float percent = 1 - (time - frameTime) / (this.frames[frameIndex + TRANSLATE_LAST_FRAME_TIME] - frameTime);
			percent = this.getCurvePercent(frameIndex / 3 - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));

			bone.scaleX += (bone.data.scaleX - 1 + lastFrameX + (this.frames[frameIndex + TRANSLATE_FRAME_X] - lastFrameX) * percent
					- bone.scaleX) * alpha;
			bone.scaleY += (bone.data.scaleY - 1 + lastFrameY + (this.frames[frameIndex + TRANSLATE_FRAME_Y] - lastFrameY) * percent
					- bone.scaleY) * alpha;
		}

		internal override float GetDuration() {
			float longest = 0;
			for (int i = 0; i < FrameCount; i++) {
				if (frames[i * 3] > longest) {
					longest = frames[i * 3];
				}
			}
			return longest;
		}
	}
}
